using System.Collections.Generic;
using Lucene.Net.Index;
using Lucene.Net.Search;
using SearchTools.Providers;

namespace SearchTools.Factories
{
    /// <summary>
    /// Concrete factory for the construction of metadata link queries
    /// </summary>
    public class LinkFactory
    {
        /// <summary>
        /// Creates meta data injection query by taking the terms supplied by the provider and constructing a query like:
        /// field:term1 field:term2 field:term3 ...
        /// </summary>
        /// <param name="providerref">The providerref.</param>
        /// <param name="field">The field.</param>
        /// <returns>A boolean query matching the terms supplied by the provider</returns>
        public static BooleanQuery Create(ProviderReference providerref, string field)
        {
            BooleanQuery res = new BooleanQuery();
            //Get provider terms
            Dictionary<string, int> rankedTerms = MetaDataResolver.GetValue(providerref);

            //Construct phrase / term queries and combine
            foreach (KeyValuePair<string, int> rankedTerm in rankedTerms)
            {
                Query q = null;
                if (rankedTerm.Key.IndexOf(' ') != -1)
                {
                    //Phrase query, this metadata value contains multiple terms
                    q = new PhraseQuery();
                    ((PhraseQuery) q).Add(new Term(field, rankedTerm.Key));
                }
                q = new TermQuery(new Term(field, rankedTerm.Key));

                q.SetBoost(rankedTerm.Value);
                res.Add(q, BooleanClause.Occur.SHOULD);
            }

            return res;
        }
    }
}